package org.znxs.comfriend.fragments;

import static android.content.ContentValues.TAG;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.SearchView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.chip.Chip;

import org.znxs.comfriend.R;
import org.znxs.comfriend.adapters.FriendCardAdapter;
import org.znxs.comfriend.models.User;
import org.znxs.comfriend.utils.AllUserList;
import org.znxs.comfriend.utils.UserUtils;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private RecyclerView rvRecommendations;
    private SearchView searchView;
    private LinearLayout tagContainer;

    // 全局数据源
    private List<User> allUsers; // 存储所有用户数据
    private List<User> filteredUsers; // 存储筛选后的用户数据


    private FriendCardAdapter adapter; // RecyclerView 的适配器

    private SwipeRefreshLayout swipeRefreshLayout; // SwipeRefreshLayout

    private boolean isRefreshing = false; // 标志位，防止重复刷新

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        // 初始化推荐用用户列表
        rvRecommendations = view.findViewById(R.id.rv_recommendations);
        setupRecommendationList();

        // 初始化分类标签
        tagContainer = view.findViewById(R.id.tag_container);
        initCategoryTags();

        // 初始化 SearchView
        searchView = view.findViewById(R.id.search_view);
        setupSearchView();

        // 初始化 SwipeRefreshLayout
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        setupSwipeRefreshLayout();


        return view;
    }

    /**
     * 初始化 SwipeRefreshLayout
     */
    private void setupSwipeRefreshLayout() {
        swipeRefreshLayout.setOnRefreshListener(() -> {
            if (!isRefreshing) {
                isRefreshing = true; // 设置为正在刷新
                refreshData();
            }
        });
    }

    private void refreshData() {
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            try {
                // 更新数据源
                UserUtils.clearUserList();
                UserUtils.generateUsers(10);


                // 模拟点击导航按钮，重新加载首页
                if (getActivity() != null) {
                    BottomNavigationView bottomNavigationView = getActivity().findViewById(R.id.bottom_navigation);
                    if (bottomNavigationView != null) {
                        bottomNavigationView.setSelectedItemId(R.id.nav_home); // 模拟点击首页按钮
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                // 停止刷新动画
                swipeRefreshLayout.setRefreshing(false);
                isRefreshing = false; // 重置标志位

                // 提示用户刷新完成
                Toast.makeText(getContext(), "数据已更新", Toast.LENGTH_SHORT).show();
            }
        }, 200); // 延迟 2 秒模拟网络请求
    }

    /**
     * 初始化推荐列表
     */
    private void setupRecommendationList() {
        rvRecommendations.setLayoutManager(new LinearLayoutManager(getContext()));

        // 获取所有用户数据
        allUsers = AllUserList.getInstance().getSharedList();
        filteredUsers = new ArrayList<>(allUsers); // 初始时显示全部用户

        // 设置适配器（传递 followedUsers）
        adapter = new FriendCardAdapter(getContext(), filteredUsers);
        rvRecommendations.setAdapter(adapter);
    }


    /**
     * 初始化分类标签
     */
    private void initCategoryTags() {
        String[] categories = getResources().getStringArray(R.array.friend_categories);

        // 遍历分类数组，创建 Chip
        for (String category : categories) {
            Chip chip = new Chip(getContext());
            chip.setText(category);
            chip.setCheckable(true); // 设置可选中
            chip.setChipBackgroundColorResource(R.color.tags_background); // 默认背景颜色
            chip.setTextColor(getResources().getColor(android.R.color.black, null)); // 文字颜色
            chip.setChipStrokeWidth(0f); // 移除边框宽度
            chip.setChipStrokeColorResource(android.R.color.transparent); // 移除边框颜色

            // 设置点击事件
            chip.setOnClickListener(v -> {
                // 更新选中状态
                updateChipSelection(chip, categories);
                // 筛选用户
                filterByCategory(category, v);
            });

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(8, 8, 8, 8);
            tagContainer.addView(chip, params);

            // 如果是 "全部"，默认选中
            if ("全部".equals(category)) {
                chip.setChecked(true);
                chip.setChipBackgroundColorResource(R.color.selected_tag_background); // 选中背景颜色
                chip.setTextColor(getResources().getColor(android.R.color.white, null)); // 选中文字颜色
            }
        }

        // 默认加载所有用户数据
        filterByCategory("全部", null);
    }

    /**
     * 更新 Chip 的选中状态
     */
    private void updateChipSelection(Chip selectedChip, String[] categories) {
        // 遍历所有 Chip，更新选中状态
        for (int i = 0; i < tagContainer.getChildCount(); i++) {
            View child = tagContainer.getChildAt(i);
            if (child instanceof Chip) {
                Chip chip = (Chip) child;
                if (chip == selectedChip) {
                    // 设置选中状态
                    chip.setChecked(true);
                    chip.setChipBackgroundColorResource(R.color.selected_tag_background); // 选中背景颜色
                    chip.setTextColor(getResources().getColor(android.R.color.white, null)); // 选中文字颜色
                } else {
                    // 恢复默认状态
                    chip.setChecked(false);
                    chip.setChipBackgroundColorResource(R.color.tags_background); // 默认背景颜色
                    chip.setTextColor(getResources().getColor(android.R.color.black, null)); // 默认文字颜色
                }
            }
        }
    }

    /**
     * 根据分类筛选
     */
    private void filterByCategory(String category, View v) {


        // 清空当前筛选结果
        filteredUsers.clear();

        if ("全部".equals(category)) {
            // 显示所有用户
            adapter.updateData(allUsers);
        } else {
            // 遍历所有用户，匹配分类
            for (User user : allUsers) {
                if (user.getCategory().equalsIgnoreCase(category)) {
                    filteredUsers.add(user);
                }
            }
            Toast.makeText(getContext(), "筛选: " + category, Toast.LENGTH_SHORT).show();
            // 更新 RecyclerView
            adapter.updateData(filteredUsers);
        }
    }


    /**
     * 设置 SearchView 的行为
     */
    private void setupSearchView() {
        searchView.setOnClickListener(v -> {
            searchView.setIconified(false); // 展开 SearchView
            searchView.requestFocus(); // 请求焦点
        });

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                performSearch(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (newText.isEmpty()) {
                    clearSearchResults();
                } else {
                    performSearch(newText);
                }
                return true;
            }
        });
    }


    /**
     * 执行搜索逻辑
     */
    private void performSearch(String query) {
        Log.d("Search", "用户搜索的内容：" + query);

        // 清空当前筛选结果
        filteredUsers.clear();

        // 遍历所有用户，匹配名称或简介
        for (User user : allUsers) {
            if (user.getNickname().toLowerCase().contains(query.toLowerCase()) || user.getBio().toLowerCase().contains(query.toLowerCase())) {
                Log.d(TAG, "加入用户" + user);
                filteredUsers.add(user);
            }
        }

        // 添加日志以验证过滤结果
        Log.d("Search", "过滤后的用户数量: " + filteredUsers.size());

        // 更新 RecyclerView
        adapter.updateData(filteredUsers);


    }

    /**
     * 清空搜索结果
     */
    private void clearSearchResults() {
        Log.d("Search", "清空搜索结果");

        // 恢复显示所有用户
        filteredUsers.clear();
        filteredUsers.addAll(allUsers);

        // 更新 RecyclerView
        adapter.updateData(filteredUsers);
    }

}